/*
 * 
 * Copyright 2011 Clean GWT
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cleangwt.showcase.client.page;

import com.cleangwt.bootstrap.client.ui.Alert;
import com.cleangwt.bootstrap.client.ui.GroupFormPanel;
import com.cleangwt.bootstrap.client.ui.Modal;
import com.cleangwt.bootstrap.client.ui.PaginationPager;
import com.cleangwt.bootstrap.client.ui.RadioField;
import com.cleangwt.bootstrap.support.client.TooltipErrorHandler;
import com.cleangwt.json.client.SimpleObject;
import com.cleangwt.page.client.PageContext.CodeSplit;
import com.cleangwt.page.client.PageContext.Page;
import com.cleangwt.page.client.PageContext.Prefetch;
import com.cleangwt.showcase.client.ProvidesSource;
import com.cleangwt.showcase.client.component.ShowcasePage;
import com.cleangwt.showcase.client.resource.DataSource;
import com.cleangwt.showcase.client.resource.PageGroups;
import com.cleangwt.showcase.client.resource.i18n.TableMessages;
import com.cleangwt.user.cellview.client.ActionColumn;
import com.cleangwt.user.cellview.client.ActionColumn.TableActionHandler;
import com.cleangwt.user.cellview.client.CheckColumn;
import com.cleangwt.user.cellview.client.CompositeColumn;
import com.cleangwt.user.cellview.client.DataGrid;
import com.cleangwt.user.cellview.client.DateColumn;
import com.cleangwt.user.cellview.client.ListColumn;
import com.cleangwt.user.cellview.client.NumberColumn;
import com.cleangwt.user.cellview.client.SelectionColumn;
import com.cleangwt.user.cellview.client.TextColumn;
import com.cleangwt.user.client.ui.Button;
import com.cleangwt.user.client.ui.DateBox;
import com.cleangwt.user.client.ui.Lay;
import com.cleangwt.user.client.ui.NumberBox;
import com.cleangwt.user.client.ui.TextBox;
import com.cleangwt.user.client.ui.ValueCallback;
import com.cleangwt.validation.client.Validator;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.builder.shared.TableRowBuilder;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.cellview.client.AbstractHeaderOrFooterBuilder;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.view.client.DefaultSelectionEventManager;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.MultiSelectionModel;

/**
 * @author Jess
 * @version 1.0
 * @since 1.0
 */
@Prefetch(PageGroups.RICH_WIDGET)
@CodeSplit
@Page
public class DataGridDemo extends ShowcasePage implements TableActionHandler, ProvidesSource {
  private class FooterBuilder extends AbstractHeaderOrFooterBuilder<SimpleObject> {

    public FooterBuilder() {
      super(dataGrid, true);
    }

    @Override
    protected boolean buildHeaderOrFooterImpl() {
      String footerStyle = dataGrid.getResources().style().footer();
      TableRowBuilder tr = startRow();
      tr.startTH().colSpan(2).className(footerStyle).text("Data Count").endTH();

      tr.startTH().className(footerStyle).align(
          HasHorizontalAlignment.ALIGN_CENTER.getTextAlignString()).text(
          String.valueOf(tableData.getList().size())).endTH();

      tr.startTH().className(footerStyle).endTH();
      tr.startTH().className(footerStyle).endTH();
      tr.endTR();
      return true;
    }

  }

  TableMessages c = GWT.create(TableMessages.class);;

  TextBox txtbName = new TextBox();
  NumberBox txtbAge = new NumberBox();
  RadioField rdfSex = new RadioField(true);
  NumberBox txtbSalary = new NumberBox(3);
  DateBox datbBirth = new DateBox();
  Button btnAdd = new Button(c.add());
  ListDataProvider<SimpleObject> tableData = new ListDataProvider<SimpleObject>();
  DataGrid dataGrid = new DataGrid(15);
  Validator validator = new Validator(new TooltipErrorHandler());

  public DataGridDemo() {
    super("The DataGrid", "To present structural data in grid.", "DataGridDemo.java");

    GroupFormPanel layout = new GroupFormPanel();

    PaginationPager pager = new PaginationPager();
    MultiSelectionModel<SimpleObject> selectionModel = new MultiSelectionModel<SimpleObject>();

    setContentWidget(layout);

    layout.build().add(c.name(), txtbName).div(4).add(c.age(), txtbAge).div(4).add(c.sex(), rdfSex)
        .div(4);
    layout.build().add(c.salary(), txtbSalary).div(4).add(c.birth(), datbBirth).div(4);

    layout.add(Lay.pullRight(Lay.p(btnAdd)));
    layout.add(Lay.height(324, Lay.hStretch(dataGrid)));
    layout.add(pager);
    dataGrid.setFooterBuilder(new FooterBuilder());

    dataGrid.addColumn(new SelectionColumn(selectionModel));
    dataGrid.addColumn(new TextColumn("name", true, true), c.name());
    dataGrid.addColumn(new NumberColumn("age"), c.age());
    // dataGrid.addColumn(new RadioColumn("sex", DataSource.getSexTypes(),false), c.sex());
    dataGrid.addColumn(new ListColumn("sex", DataSource.getSexTypes(), false), c.sex());
    dataGrid.addColumn(new CheckColumn("interesting", DataSource.getInterestings()), c
        .interesting());
    dataGrid.addColumn(new DateColumn("birth", true, true), c.birth());
    dataGrid.addColumn(new NumberColumn("salary"), c.salary());
    dataGrid.addColumn(new CompositeColumn(new ActionColumn(c.hello(), "hello", this),
        new ActionColumn(c.delete(), "bye", this)), c.action());

    dataGrid.setColumnWidth(0, "60px");
    dataGrid.setColumnWidth(1, "200px");
    dataGrid.setColumnWidth(2, "120px");
    dataGrid.setColumnWidth(3, "180px");
    dataGrid.setColumnWidth(4, "400px");
    dataGrid.setColumnWidth(5, "240px");
    dataGrid.setColumnWidth(6, "160px");
    dataGrid.setColumnWidth(7, "160px");
    dataGrid.setSelectionModel(selectionModel, DefaultSelectionEventManager
        .<SimpleObject> createCheckboxManager(0));

    pager.setDisplay(dataGrid);
    tableData.addDataDisplay(dataGrid);

    validator.build(txtbName).notNull();
    validator.build(txtbSalary).notNull();

    btnAdd.addClickHandler(new ClickHandler() {

      @Override
      public void onClick(ClickEvent event) {
        addUser();
      }
    });

    rdfSex.setOptions(DataSource.getSexTypes());
    // for (int i = 0; i < 20; i++) {
    // SimpleObject user = new SimpleObject();
    // user.put("age", i);
    // user.put("name", "name " + i);
    // user.put("salary", 10000 * i);
    // tableData.getList().add(user);
    // }
  }

  private void addUser() {
    if (validator.validate()) {
      SimpleObject s = getNewUser();
      tableData.getList().add(s);
      // reset
      txtbName.setValue(null);
      txtbAge.setValue(null);
      rdfSex.setValue(null);
      txtbSalary.setValue(null);
      datbBirth.setValue(null);
      validator.reset();
    }
  }

  private SimpleObject getNewUser() {
    SimpleObject user = new SimpleObject();
    user.put("age", txtbAge.getValue());
    user.put("sex", rdfSex.getValue());
    user.put("name", txtbName.getValue());
    user.put("salary", txtbSalary.getValue());
    user.put("birth", datbBirth.getValue());
    return user;
  }

  public void onTableAction(String action, int index, final SimpleObject rowData) {
    if ("hello".equals(action)) {
      Alert.alert(c.sayHello((String) rowData.get("name")));
    } else if ("bye".equals(action)) {
      Modal.confirm(c.confirm(), new ValueCallback<String>() {

        @Override
        public void onValueCallback(String option) {
          tableData.getList().remove(rowData);
        }
      });
    }
  }

}
